package com.dingyuhang.controller;


import com.dingyuhang.bean.Forum;
import com.dingyuhang.bean.User;
import com.dingyuhang.service.ForumService;
import com.dingyuhang.service.TopicService;
import com.dingyuhang.service.UserService;
import com.dingyuhang.util.MyAnn;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private ForumService forumService;

    @Autowired
    private TopicService topicService;


    /**
     * 后台首页
     * @param model
     * @return
     */
    @RequestMapping({"", "/", "/index"})
    public String home(Model model) {

        //统计信息：用户数
        int users = userService.count(null);
        model.addAttribute("users", users);

        //统计信息：帖子数
        int topics = topicService.countTopics(null);
        model.addAttribute("topics", topics);

        return "admin/index";
    }


    /**
     * 用户列表
     * @param model
     * @return
     */
    @RequestMapping("/users")
    public String users(Model model,@RequestParam(defaultValue="1")Integer pageNum) {
    	PageInfo<User> pageInfo = userService.selectUsers(pageNum);
    	model.addAttribute("pageInfo", pageInfo);
        return "admin/user_list";
    }


    /**
     * 版块列表
     * @param model
     * @return
     */
    @MyAnn
    @RequestMapping("/forums")
    public String forums(Model model) {
       model.addAttribute("forums", forumService.selectForums());
        return "admin/forum_list";
    }


    /**
     * 版块开设/修改
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/forum/edit")
    public String addForum(@RequestParam(required = false) Integer id, Model model) {
        Forum forum = null;
        if (id == null) {
            forum = new Forum();
            int sorted = forumService.maxSortNo(); //查询出最大的排序
            forum.setSorted(++sorted);//给最大的序号加1
        } else {
            forum = forumService.getForumById(id);//根据id查询
        }
        model.addAttribute("forum", forum);
        return "admin/forum_edit";
    }


    /**
     * 版块数据保存
     * @param forum
     * @param errors
     * @param model
     * @return
     */
    @PostMapping("/forum/save")
    public String saveForum(@Valid @ModelAttribute Forum forum, BindingResult errors, Model model) {
        if(errors.hasErrors()){
            return "admin/forum_edit";
        }
        if(forum.getId() == null){
            forumService.insertForum(forum);
        }else{
           forumService.updateForum(forum);
        }
        return "redirect:/admin/forums";
    }
}
